/*
 * @Author: yao
 * @Date: 2022-11-19 12:57:38
 * @LastEditTime: 2025-02-18 17:23:38
 * @LastEditors: yao
 * @Description: 生成动态路由
 * @FilePath: \jdev-web-el\src\router\generator-router.ts
 */
import BaseLayout from "@/layouts/BaseLayout.vue";
import { useUserStore } from "@/stores/modules/user";

const modules = import.meta.glob("../views/**/*.vue");

export const generatorDynamicRouter = (mData: any) => {
  return new Promise((resolve, reject) => {
    try {
      const accessedRoutes = generator(mData);
      const userStore = useUserStore();
      userStore.setRoutes(accessedRoutes);
      resolve(accessedRoutes);
    } catch (err) {
      reject(err);
    }
  });
};

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list: [], tree: any, parentId = "0") => {
  list.forEach((item: any) => {
    if (item.id === parentId) {
      const child = {
        ...item,
        children: [],
      };
      listToTree(list, child.children, item.id);
      if (child.children.length <= 0) {
        delete child.children;
      }
      tree.push(child);
    }
  });
};

export const generator = (routerMap: any) => {
  return routerMap.map((item: any) => {
    const currentRouter: any = {
      id: item.id,
      path: item.path,
      name: item.name,
      redirect: item.redirectUrl ? item.redirectUrl : "",
      meta: {
        id: item.id,
        title: item.title,
        close: item.menuClose == 0 ? false : true,
        icon: item.icon,
        sort: item.sort,
        type: item.meta.type || 'page',
        hidden: item.visible == 0 ? false : true,
      },
    };
    if (item.category === "MODULE") {
      currentRouter.component = BaseLayout;
    } else {
      if (item.component) {
        const component = modules[`../views/${item.component}`];
        if (component) {
          currentRouter.component = component;
        } else {
          currentRouter.component = modules[`../views/404.vue`];
        }
      } else {
        currentRouter.component = modules[`../views/404.vue`];
      }
    }

    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children);
    }
    return currentRouter;
  });
};
